package com.bw.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.bw.domain.Role;
import com.bw.domain.User;
import com.bw.domain.UserMoney;
import com.bw.exception.MyRuntimeException;
import com.bw.service.UserService;
import com.bw.utils.AesUtil;
import com.bw.utils.MyEx;
import com.bw.utils.R;
import com.bw.utils.esypoi.ExportsUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.management.relation.RoleList;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author bobo棒
 * @date 2025年02月21日 15:52
 */

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * @param user
     * @return
     */
    @RequestMapping("updateStatus")
    @ResponseBody
    public R updateStatus(User user) {
        int i = userService.updateStatus(user);
        return i > 0 ? R.OK() : R.ERROR(500, "修改失败");


    }


    /**
     * 用户修改
     *
     * @param user
     * @return
     */
    @RequestMapping("edit")
    @ResponseBody
    public R edit(User user) {

        //用户名非空校验
        if (StringUtils.isEmpty(user.getUsername())) {
            throw new MyRuntimeException("用户名不能为空");
        }
        if (StringUtils.isEmpty(user.getPhone())) {
            throw new MyRuntimeException("手机号不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            throw new MyRuntimeException("密码不能为空");
        }
        if (StringUtils.isEmpty(user.getIdcard())) {
            throw new MyRuntimeException("身份证不能为空");
        }

        int i = userService.update(user);
        return i > 0 ? R.OK() : R.ERROR(500, "修改失败");


    }


    /**
     * 用户充值
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("recharge")
    public R recharge(UserMoney userMoney) throws MyEx {

        boolean b = userService.recharge(userMoney);
        return b ? R.OK() : R.ERROR(500, "充值失败");
    }

    /**
     * 跳转到用户充值页面
     *
     * @return
     */
    @RequestMapping("toRecharge")
    public String toRecharge(String id, String username, Model model) {
        model.addAttribute("userId", id);
        model.addAttribute("username", username);
        return "user/recharge";
    }


    /**
     * 获取所有角色
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("listRole")
    public R listRole() {
        List<Role> roleList = userService.listRole();

        return R.OK(roleList);
    }

    /**
     * 用户修改
     *
     * @return
     */
    @RequestMapping("toedit")
    public String toedit(String id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user", user);
        //获取当前用户用户的角色信息
        List<Role> roleList = userService.listRoleByUserId(id);
        model.addAttribute("roleList", JSON.toJSON(roleList));

        return "user/edit";
    }

    //AES 秘钥
    public static final String key = "1234567890123456";

    @ResponseBody
    @RequestMapping("list")
    public R list(User user, Integer page, Integer limit) throws Exception {
        PageHelper.startPage(page, limit);
        List<User> userList = userService.list(user);
        //使用AES加密
        for (User user1 : userList) {
            //身份证加密
            user1.setIdcard(AesUtil.encrypt(user1.getIdcard(), key));
        }

        PageInfo<User> info = new PageInfo<>(userList);

        return R.OK(info);
    }

    /**
     * 用户列表
     *
     * @return
     */
    @RequestMapping("tolist")
    public String tolist() {
        return "user/list";
    }


    /**
     * 用户列表
     *
     * @return
     */
    @RequestMapping("torechargelist")
    public String torechargelist() {
        return "user/rechargelist";
    }


    /**
     * 充值列表明细
     *
     * @param page
     * @param limit
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("rechargelist")
    public R rechargelist(UserMoney userMoney, Integer page, Integer limit, HttpSession session) throws Exception {
        //普通用户只能看到自己的充值记录

        //获取当前用户的角色信息
        List<Role> roleList = (List<Role>) session.getAttribute("roleList");
        //标记是否是管理员
        boolean isadmin = false;
        for (Role role : roleList) {
            if (role.getName().equals("管理员")) {
                isadmin = true;
                break;
            }
        }
        if (!isadmin) {//如果不是管理.则只能看到自己的充值记录
            User user = (User) session.getAttribute("user");
            userMoney.setUserId(user.getId());
        }


        PageHelper.startPage(page, limit);
        List<UserMoney> list = userService.listRecharge(userMoney);


        PageInfo<UserMoney> info = new PageInfo<>(list);

        return R.OK(info);
    }


    /**
     * 导出所有数据
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("exportAllExcel")
    public R exportExcel(HttpServletResponse response) {
        //查询所有用户
        List<User> userList = userService.list(null);
        //调用工具类
        ExportsUtil.exports(response, User.class, userList, "用户列表", "用户信息", "user");
        return R.OK();
    }

    @ResponseBody
    @RequestMapping("exportExcelByCondition")
    public R exportExcel2(HttpServletResponse response,String ids) {
        //查询所有用户
        List<User> userList = userService.listByIds(ids);
       //导出文件名 固定名称+当前时间+随机数
        String exportFilename="export-"+ DateUtil.today()+"-" +RandomUtil.randomNumbers(4);
        //调用工具类
        ExportsUtil.exports(response, User.class, userList, "用户列表", "用户信息", exportFilename);
        return R.OK();
    }
}


